package db

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"choujiang/common/utils"
	"strconv"
)

type Mongodb struct {
	Connect string //连接字符串
}

type ShareToken struct {
	Id       bson.ObjectId `bson:"_id"`
	UserId   int64         `form:"userid"`
	Token    string        `form:"token"`
	GoodsId  int64         `form:"goodsid"`
	DateTime string        `form:"datetime"`
}

type SdkToken struct {
	Id         bson.ObjectId `bson:"_id"`
	UserId     int64         `form:"userid"`
	Token      string        `form:"token"`
	ToGame     string        `form:"togame"`
	Avatar     string        `form:"avatar"`
	Nickname   string        `fomr:"nickname"`
	ShareToken string        `form:"sharetoken"`
}

type TaskInfo struct {
	Id                      bson.ObjectId `bson:"_id"`
	UserId                  int64         `json:"userid"`
	DateTime                string        `json:"datetime"`
	TotalDone               int           `json:"totaldone"`               //任务完成总数
	IsSignUp                int           `json:"issignup"`                //签到任务
	IsShareGroup            int           `json:"issharegroup"`            //分享到一个群任务
	IsShareThreeGroups      int           `json:"issharethreegroups"`      //分享到三个不同群任务
	ShareGroupNum           int           `json:"sharegroupnum"`           //分享群数量
	IsPlayThreeGames        int           `json:"isplaythreegames"`        //玩3款小游戏任务
	IsPlayFiveGames         int           `json:"isplayfivegames"`         //玩5款小游戏任务
	PlayGamesNum            int           `json:"playgamesnum"`            //玩游戏数量
	IsInviteThreeFriends    int           `json:"isinvitethreefriends"`    //邀请3位好友任务
	InviteFriendsNum        int           `json:"invitefriendsnum"`        //邀请好友数量
	IsInviteThreeFriendsNew int           `json:"isinvitethreefriendsnew"` //邀请3位好友的新任务
	InviteFriendsNumNew     int           `json:"invitefriendsnumnew"`     //邀请好友数量新任务
	IsPlaySixGames          int           `json:"isplaysixgames"`          //游玩6个游戏任务
	PlayGamesNumNew         int           `json:"playgamesnumnew"`         // 游玩6跟游戏任务 总数
}

type NewTaskInfo struct {
	Id                      bson.ObjectId `bson:"_id"`
	UserId                  int64         `json:"userid"`
	IsInviteThreeFriendsNew int           `json:"isinvitethreefriendsnew"` //邀请3位好友的新任务
	InviteFriendsNumNew     int           `json:"invitefriendsnumnew"`     //邀请好友数量新任务
	IsPlaySixGames          int           `json:"isplaysixgames"`          //游玩6个游戏任务
	PlayGamesNumNew         int           `json:"playgamesnumnew"`         // 游玩6跟游戏任务 总数
}

type SceneString struct {
	Id      bson.ObjectId `bson:"_id"`
	UserId  int64         `json:"userid"`
	GoodsId int64         `json:"goodsid"`
	Scene   string        `json:"scene"`
	Channel string        `json:"channel"`
}

type LotteryLog struct {
	Id       bson.ObjectId `bson:"_id"`
	UserId   int64         `json:"userid"`
	AwardId  int64         `json:"awardid"`
	DateTime string        `json:"datetime"`
	Type     int64         `json:"type"`
	Value    float64       `json:"value"`
}

type CoinsLog struct {
	Id         bson.ObjectId `bson:"_id"`
	UserId     int64         `json:"userid"`
	Type       int64         `json:"type"`
	DateTime   int64         `json:"datetime"`
	Desc       string        `json:"desc"`
	Player     string        `json:"player"`
	Game       string        `json:"game"`
	Coins      float64       `json:"coins"`
	TimeFormat string        `json:"timeformat"`
}

type GameClick struct {
	Id       bson.ObjectId `bson:"_id"`
	UserId   int64         `json:"userid"`
	DateTime string        `json:"datetime"`
}

type ChannelClick struct {
	Id       bson.ObjectId `bson:"_id"`
	DateTime string        `json:"datetime"`
	Amount   int64         `json:"amount"`
	User     int64         `json:"user"`
}

type GameDetail struct {
	Id       bson.ObjectId `bson:"_id"`
	DateTime string        `json:"datetime"`
	Amount   int64         `json:"amount"`
}

type UserReward struct {
	Id     bson.ObjectId `bson:"_id"`
	UserId int64         `json:"userid"`
	Reward int64         `json:"reward"`
}

type SdkUserReward struct {
	Id          bson.ObjectId `bson:"_id"`
	Inviter     int64         `json:"inviter"`
	Player      int64         `json:"player"`
	Avatar      string        `json:"avatar"`
	Nickname    string        `json:"nickname"`
	OpenId      string        `json:"openid"`
	GameId      string        `json:"gameid"`
	GameName    string        `json:"gamename"`
	InviterEarn float64       `json:"inviterearn"`
	PlayerEarn  float64       `json:"playerearn"`
	DateTime    int64         `json:"datetime"`
	AppId       string        `json:"appid"`
	FormatDate  string        `json:"formatdate"`
	Channel     string        `json:"channel"`
}

type ChannelBackground struct {
	Id         bson.ObjectId `bson:"_id"`
	Channel    string        `json:"channel"`
	Background string        `json:"background"`
}

type ActiveUserLog struct {
	Id       bson.ObjectId `bson:"_id"`
	DlId     string        `json:"dlid"`
	DateTime string        `json:"datetime"`
	Count    int64         `json:"count"`
}

var (
	mgoSession    *mgo.Session
	Mgo           *Mongodb
	COLL_NOW_DATE = ""
)

const (
	COLL_TIME_FORMAT          = "2006-01-02"
	SIGN_UP_TASK              = 1                                    //签到任务
	SHARE_GROUP_TASK          = 2                                    //分享一个群
	SHARE_THREE_GROUP_TASK    = 3                                    //分享三个群
	PLAY_THREE_GAME_TASK      = 4                                    //玩三个游戏任务
	PLAY_FIVE_GAME_TASK       = 5                                    //玩五个游戏任务
	INVITE_FRIEND_TASK        = 6                                    //邀请三个玩家任务
	NEW_INVITE_FRIEND_TASK    = 7                                    //邀请三个玩家任务（第二个盒子）
	PLAY_SIX_GAME_TASK        = 8                                    //游玩6个游戏任务（第二个盒子）
	TASK_INFO_COLLECTION      = "BoxCollection::taskinfo"            //每日任务记录
	LOTTERY_COLLECTION        = "BoxCollection::lotterylog"          //抽奖记录日志
	SCENE_CHANNEL_COLLECTION  = "BoxCollection::scenechannel"        //scene channel对应记录
	PERMANENTTASK             = "BoxCollection::permanenttask"       //永久任务记录
	COLL_CHANNEL_PLAY_DETAIL  = "BoxCollection::channelplaydetail_"  //渠道详情记录
	COLL_GAME_EFFECTIVE_CLICK = "BoxCollection::gameeffectiveclick_" //游戏有效点击记录
	COLL_GAME_DETAIL          = "BoxCollection::gamedetail_"         //游戏详情统计
	COLL_USER_GAME_REWARD     = "BoxCollection::usergamereward_"     //用户游戏奖励金币
	COLL_SDK_TOKEN            = "BoxCollection::sdktoken"            //sdk跳转token记录
	COLL_USER_SDK_GAME_LOG    = "BoxCollection::usersdkgamelog"      //用户sdk游戏奖励记录
	COLL_CHANNEL_BACKGROUND   = "BoxCollection::channelbackground"   //渠道和背景图的关联
	DAILI_ACTIVE_USER_LOG     = "MpCollection::dailiactiveuserlog"   //代理活跃用户统计
)

func InitMgoDB() error {
	conncet := os.Getenv("MONGODB_HOST")
	Mgo = &Mongodb{Connect: conncet}
	mgoSession2, err := mgo.Dial(conncet)
	mgoSession = mgoSession2
	if err != nil {
		fmt.Printf("InitMgoDB err:%+v\n", err)
		return err
	}
	if mgoSession != nil {
		fmt.Printf("mgoSession:%+v\n", mgoSession)

	}
	mgoSession.SetMode(mgo.Eventual, true) //设置一致性模式
	return err
}

func getSession() *mgo.Session {
	fmt.Printf("getSession:%+v\n", mgoSession)
	return mgoSession.Copy()
}

func (m *Mongodb) Log(f func(*mgo.Collection)) {
	fmt.Printf("Log(f func\n")
	now := time.Now()
	now_date := now.Format(COLL_TIME_FORMAT)
	newDate := false
	if now_date != COLL_NOW_DATE {
		COLL_NOW_DATE = now_date
		newDate = true
	}
	session := getSession()
	defer session.Close()
	collName := fmt.Sprintf("log-%s", COLL_NOW_DATE)
	c := session.DB("leyoubox").C(collName)
	if newDate {

		index := mgo.Index{
			Key:        []string{"uniqueid", "openid", "togame", "fromgame", "logtype", "type", "plat"},
			Background: true,
		}

		c.EnsureIndex(index)
	}
	f(c)
}

/**
 获取每日的分享token
 */
func (m *Mongodb) GenToken(collName string, userId, goodsId int64) string {
	var reToken string
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(collName)
	count, _ := c.Find(bson.M{"userid": userId, "goodsid": goodsId, "datetime": utils.TodayUnix()}).Count()
	if count == 0 { //没有对应商品分享的token
		reToken = utils.GenShareToken()
		shareToken := ShareToken{}
		shareToken.Id = bson.NewObjectId()
		shareToken.UserId = userId
		shareToken.GoodsId = goodsId
		shareToken.Token = reToken
		shareToken.DateTime = utils.TodayUnix()
		if err := c.Insert(shareToken); err != nil {
			fmt.Printf("c.Insert(b) err:%+v\n", err)
		}
	} else { //已有token，返回
		result := ShareToken{}
		c.Find(bson.M{"userid": userId, "goodsid": goodsId, "datetime": utils.TodayUnix()}).One(&result)
		reToken = result.Token
	}
	return reToken
}

func (m *Mongodb) GenSdkToken(userId int64, toGame, shareToken, avatar, nickname string) string {
	var reToken string
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_SDK_TOKEN)
	reToken = utils.GenShareToken()
	token := SdkToken{}
	token.Id = bson.NewObjectId()
	token.UserId = userId
	token.Token = reToken
	token.ToGame = toGame
	token.ShareToken = shareToken
	token.Avatar = avatar
	token.Nickname = nickname
	if err := c.Insert(token); err != nil {
		fmt.Printf("c.Insert(b) err:%+v\n", err)
	}
	return reToken
}

/**
 获取用户每日任务完成详情
 */
func (m *Mongodb) GetTaskInfo(userId int64) TaskInfo {
	taskInfo := TaskInfo{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(TASK_INFO_COLLECTION)
	count, _ := c.Find(bson.M{"userid": userId, "datetime": utils.TodayUnix()}).Count()
	if count == 0 { //没有记录
		taskInfo.Id = bson.NewObjectId()
		taskInfo.UserId = userId
		taskInfo.DateTime = utils.TodayUnix()
		taskInfo.TotalDone = 0
		taskInfo.IsSignUp = 0
		taskInfo.IsShareGroup = 0
		taskInfo.IsShareThreeGroups = 0
		taskInfo.ShareGroupNum = 0
		taskInfo.IsPlayThreeGames = 0
		taskInfo.IsPlayFiveGames = 0
		taskInfo.PlayGamesNum = 0
		taskInfo.IsInviteThreeFriends = 0
		taskInfo.InviteFriendsNum = 0
		if err := c.Insert(taskInfo); err != nil {
			fmt.Printf("c.Insert(b) err:%+v\n", err)
		}
	} else { //有记录
		c.Find(bson.M{"userid": userId, "datetime": utils.TodayUnix()}).One(&taskInfo)
	}
	return taskInfo
}

func (m *Mongodb) GetNewTaskInfo(userId int64) NewTaskInfo {
	taskInfo := NewTaskInfo{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(PERMANENTTASK)
	count, _ := c.Find(bson.M{"userid": userId}).Count()
	if count == 0 { //没有记录
		taskInfo.Id = bson.NewObjectId()
		taskInfo.InviteFriendsNumNew = 0
		taskInfo.IsInviteThreeFriendsNew = 0
		taskInfo.PlayGamesNumNew = 0
		taskInfo.IsPlaySixGames = 0
		taskInfo.UserId = userId
		if err := c.Insert(taskInfo); err != nil {
			fmt.Printf("c.Insert(b) err:%+v\n", err)
		}
	} else { //有记录
		c.Find(bson.M{"userid": userId}).One(&taskInfo)
	}
	return taskInfo
}

/**
 判断token是否合法
 */
func (m *Mongodb) TokenExist(collName string, shareToken string) (ShareToken, int) {
	result := ShareToken{}
	var reInt int
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(collName)
	count, err := c.Find(bson.M{"token": shareToken}).Count()
	if err != nil {
		fmt.Printf("collName---------- %s shareToken:%s TokenExist err %s \n", collName, shareToken, err)
	}
	if count != 0 {
		c.Find(bson.M{"token": shareToken}).One(&result)
		reInt = 1
	}
	fmt.Printf("collName %s shareToken:%s result:%+v count:%d \n", collName, shareToken, result, count)

	return result, reInt
}

func (m *Mongodb) CheckSdkToken(token string) (SdkToken, int) {
	result := SdkToken{}
	reInt := 0
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_SDK_TOKEN)
	var count = 0
	count, _ = c.Find(bson.M{"token": token}).Count()
	if count != 0 {
		c.Find(bson.M{"token": token}).One(&result)
		reInt = 1
	}
	return result, reInt
}

func (m *Mongodb) OpenIdValidate(openId, toGame string) bool {
	result := false
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	var count = 0
	count, _ = c.Find(bson.M{"openid": openId, "gameid": toGame}).Count()
	if count != 0 {
		result = true
	}
	return result
}

func (m *Mongodb) UserIdValidate(userId int64, toGame string) bool {
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	var count = 0
	count, _ = c.Find(bson.M{"player": userId, "gameid": toGame}).Count()
	if count != 0 {
		return true
	}
	return false
}

func (m *Mongodb) SdkRewardLog(inviterId, playerId int64, avatar, nickname, openId, gameId, gameName string, inviterEarn, playerEarn float64, dateTime int64, appId, fromChannel string) {
	reward := SdkUserReward{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	reward.Id = bson.NewObjectId()
	reward.OpenId = openId
	reward.GameId = gameId
	reward.GameName = gameName
	reward.Inviter = inviterId
	reward.Player = playerId
	reward.Avatar = avatar
	reward.Nickname = nickname
	reward.InviterEarn = inviterEarn
	reward.PlayerEarn = playerEarn
	reward.DateTime = dateTime
	reward.AppId = appId
	reward.Channel = fromChannel
	if err := c.Insert(reward); err != nil {
		fmt.Printf("c.Insert(b) err:%+v\n", err)
	}
	index := mgo.Index{
		Key:        []string{"openid", "gameid", "appid"},
		Background: true,
	}
	c.EnsureIndex(index)

	return
}

/**
 记录更新任务完成信息
 */
func (m *Mongodb) CompleteTask(userId int64, taskType int64, isDone bool) {
	taskInfo := TaskInfo{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(TASK_INFO_COLLECTION)
	count, _ := c.Find(bson.M{"userid": userId, "datetime": utils.TodayUnix()}).Count()
	if count == 0 {
		taskInfo.Id = bson.NewObjectId()
		taskInfo.UserId = userId
		taskInfo.DateTime = utils.TodayUnix()
		taskInfo.TotalDone = 0
		taskInfo.IsSignUp = 0
		taskInfo.IsShareGroup = 0
		taskInfo.IsShareThreeGroups = 0
		taskInfo.ShareGroupNum = 0
		taskInfo.IsPlayThreeGames = 0
		taskInfo.IsPlayFiveGames = 0
		taskInfo.PlayGamesNum = 0
		taskInfo.IsInviteThreeFriends = 0
		taskInfo.InviteFriendsNum = 0
		taskInfo.IsInviteThreeFriendsNew = 0
		taskInfo.InviteFriendsNumNew = 0
		taskInfo.IsPlaySixGames = 0
		taskInfo.PlayGamesNumNew = 0
		if err := c.Insert(taskInfo); err != nil {
			fmt.Printf("c.Insert(b) err:%+v\n", err)
		}
	} else {
		c.Find(bson.M{"userid": userId, "datetime": utils.TodayUnix()}).One(&taskInfo)
	}
	switch taskType {
	case SIGN_UP_TASK: //签到任务
		err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"issignup": 1, "totaldone": taskInfo.TotalDone + 1}});
		if err != nil {
			fmt.Printf("c.Update(b) err:%+v\n", err)
		}
	case SHARE_GROUP_TASK: //分享群任务
		err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"issharegroup": 1, "totaldone": taskInfo.TotalDone + 1, "sharegroupnum": taskInfo.ShareGroupNum + 1}});
		if err != nil {
			fmt.Printf("c.Update(b) err:%+v\n", err)
		}
	case SHARE_THREE_GROUP_TASK: //分享三个群任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"issharethreegroups": 1, "totaldone": taskInfo.TotalDone + 1, "sharegroupnum": taskInfo.ShareGroupNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"sharegroupnum": taskInfo.ShareGroupNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	case PLAY_THREE_GAME_TASK: //玩三个游戏任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplaythreegames": 1, "totaldone": taskInfo.TotalDone + 1, "playgamesnum": taskInfo.PlayGamesNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"playgamesnum": taskInfo.PlayGamesNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	case PLAY_FIVE_GAME_TASK: //玩五个游戏任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplayfivegames": 1, "totaldone": taskInfo.TotalDone + 1, "playgamesnum": taskInfo.PlayGamesNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"playgamesnum": taskInfo.PlayGamesNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	case INVITE_FRIEND_TASK: //邀请三个好友任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isinvitethreefriends": 1, "totaldone": taskInfo.TotalDone + 1, "invitefriendsnum": taskInfo.InviteFriendsNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"invitefriendsnum": taskInfo.InviteFriendsNum + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	case NEW_INVITE_FRIEND_TASK: //邀请三个好友任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isinvitethreefriendsnew": 1, "invitefriendsnumnew": taskInfo.InviteFriendsNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"invitefriendsnumnew": taskInfo.InviteFriendsNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	case PLAY_SIX_GAME_TASK: //游玩6个游戏任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplaysixgames": 1, "playgamesnumnew": taskInfo.PlayGamesNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"playgamesnumnew": taskInfo.PlayGamesNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	}
}

func (m *Mongodb) CompleteNewTask(userId int64, taskType int64, isDone bool) {
	taskInfo := NewTaskInfo{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(PERMANENTTASK)
	count, _ := c.Find(bson.M{"userid": userId}).Count()
	if count == 0 {
		taskInfo.Id = bson.NewObjectId()
		taskInfo.IsInviteThreeFriendsNew = 0
		taskInfo.InviteFriendsNumNew = 0
		taskInfo.IsPlaySixGames = 0
		taskInfo.PlayGamesNumNew = 0
		taskInfo.UserId = userId
		if err := c.Insert(taskInfo); err != nil {
			fmt.Printf("c.Insert(b) err:%+v\n", err)
		}
	} else {
		c.Find(bson.M{"userid": userId}).One(&taskInfo)
	}
	switch taskType {
	case NEW_INVITE_FRIEND_TASK: //邀请三个好友任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isinvitethreefriendsnew": 1, "invitefriendsnumnew": taskInfo.InviteFriendsNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"invitefriendsnumnew": taskInfo.InviteFriendsNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	case PLAY_SIX_GAME_TASK: //游玩6个游戏任务
		if isDone {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplaysixgames": 1, "playgamesnumnew": taskInfo.PlayGamesNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		} else {
			err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"playgamesnumnew": taskInfo.PlayGamesNumNew + 1}});
			if err != nil {
				fmt.Printf("c.Update(b) err:%+v\n", err)
			}
		}
	}
}

func (m *Mongodb) TakeRedPack(userId int64, types int) bool {
	taskInfo := NewTaskInfo{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(PERMANENTTASK)
	c.Find(bson.M{"userid": userId}).One(&taskInfo)
	if types == 1 {
		if taskInfo.IsInviteThreeFriendsNew == 1 {
			return true
		}
	} else {
		if taskInfo.IsPlaySixGames == 1 {
			return true
		}
	}
	return false
}

/**
 补充任务完成信息
 */
func (m *Mongodb) SuplementTask(userId int64, taskType int64) {
	taskInfo := TaskInfo{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(TASK_INFO_COLLECTION)
	c.Find(bson.M{"userid": userId, "datetime": utils.TodayUnix()}).One(&taskInfo)
	switch taskType {
	case PLAY_THREE_GAME_TASK: //玩三个游戏任务
		err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplaythreegames": 1}});
		if err != nil {
			fmt.Printf("c.Update(b) err:%+v\n", err)
		}
	case PLAY_FIVE_GAME_TASK: //玩五个游戏任务
		err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplayfivegames": 1}});
		if err != nil {
			fmt.Printf("c.Update(b) err:%+v\n", err)
		}
	case PLAY_SIX_GAME_TASK: //玩六个游戏任务
		err := c.Update(bson.M{"_id": taskInfo.Id}, bson.M{"$set": bson.M{"isplaysixgames": 1}});
		if err != nil {
			fmt.Printf("c.Update(b) err:%+v\n", err)
		}
	}
}

/**
 记录抽奖日志
 */
func (m *Mongodb) LogLottery(userId int64, aType int64, aValue float64, aId int64) {
	lotteryLog := LotteryLog{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(LOTTERY_COLLECTION)
	lotteryLog.Id = bson.NewObjectId()
	lotteryLog.UserId = userId
	lotteryLog.AwardId = aId
	lotteryLog.DateTime = utils.TodayUnix()
	lotteryLog.Type = aType
	lotteryLog.Value = aValue
	if err := c.Insert(lotteryLog); err != nil {
		fmt.Printf("c.Insert(b) err:%+v\n", err)
	}
}

func (m *Mongodb) GetChannelFromScene(scene string) string {
	sceneString := SceneString{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(SCENE_CHANNEL_COLLECTION)
	count, _ := c.Find(bson.M{"scene": scene}).Count()
	if count != 0 {
		c.Find(bson.M{"scene": scene}).One(&sceneString)
	}
	return sceneString.Channel
}

func (m *Mongodb) GetUserIdFromScene(scene string) int64 {
	sceneString := SceneString{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(SCENE_CHANNEL_COLLECTION)
	count, _ := c.Find(bson.M{"scene": scene}).Count()
	if count != 0 {
		c.Find(bson.M{"scene": scene}).One(&sceneString)
	}
	return sceneString.UserId
}

func (m *Mongodb) GetGoodsIdFromScene(scene string) int64 {
	sceneString := SceneString{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(SCENE_CHANNEL_COLLECTION)
	count, _ := c.Find(bson.M{"scene": scene}).Count()
	if count != 0 {
		c.Find(bson.M{"scene": scene}).One(&sceneString)
	}
	return sceneString.GoodsId
}

/**
 获取金币记录
 */
func (m *Mongodb) GetCoinsLog(userId int64, coll string, pageNo, pageSize int) []CoinsLog {
	coinsLog := []CoinsLog{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(coll)
	count, _ := c.Find(bson.M{"userid": userId}).Count()
	if count != 0 {
		curPageNo := (pageNo - 1) * pageSize
		c.Find(bson.M{"userid": userId}).Skip(curPageNo).Limit(pageSize).Sort("-datetime").All(&coinsLog)
	}
	return coinsLog
}

func (m *Mongodb) GetEarnLog(userId int64, pageNo, pageSize int) []SdkUserReward {
	earnLog := []SdkUserReward{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	count, _ := c.Find(bson.M{"$or": []bson.M{{"inviter": userId}, {"player": userId}}}).Count()
	if count != 0 {
		curPageNo := (pageNo - 1) * pageSize
		c.Find(bson.M{"$or": []bson.M{{"inviter": userId}, {"player": userId}}}).Skip(curPageNo).Limit(pageSize).Sort("-datetime").All(&earnLog)
	}
	return earnLog
}

/**
 记录金币收支日志
 */
func (m *Mongodb) WriteCoinsLog(userId int64, coll string, player, game, desc string, coins float64) {
	coinsLog := CoinsLog{}
	t := time.Now()
	tUnix := t.Unix()
	tFormat := utils.FormatDate(tUnix)
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(coll)
	coinsLog.Id = bson.NewObjectId()
	coinsLog.Coins = coins
	coinsLog.UserId = userId
	coinsLog.Player = player
	coinsLog.Game = game
	coinsLog.Desc = desc
	coinsLog.Type = 1
	coinsLog.DateTime = tUnix
	coinsLog.TimeFormat = tFormat
	if err := c.Insert(coinsLog); err != nil {
		fmt.Printf("c.Insert(b) err:%+v\n", err)
	}
}

/**
 记录有效点击次数
 */
func (m *Mongodb) RecordPlayDetail(userId int64, channel string, gameId string) {
	clickColl := COLL_GAME_EFFECTIVE_CLICK + gameId //有效点击coll
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(clickColl)
	count, _ := c.Find(bson.M{"userid": userId}).Count()
	if count == 0 { //有效点击
		tFormat := utils.TodayUnix()
		gameClick := GameClick{}
		gameClick.Id = bson.NewObjectId()
		gameClick.UserId = userId
		gameClick.DateTime = tFormat
		if err := c.Insert(gameClick); err != nil {
			fmt.Printf("c.Insert(b) err:%+v\n", err)
		}
		channelColl := COLL_CHANNEL_PLAY_DETAIL + channel
		s := session.DB("leyoubox").C(channelColl)
		count, _ := s.Find(bson.M{"datetime": tFormat}).Count()
		channelClick := ChannelClick{}
		if count == 0 { //没统计过
			channelClick.Id = bson.NewObjectId()
			channelClick.DateTime = tFormat
			channelClick.Amount = 1 //初始化统计数量
			channelClick.User = 0   //用户数量
			if err := s.Insert(channelClick); err != nil {
				fmt.Printf("c.Insert(s) err:%+v\n", err)
			}
		} else {
			s.Find(bson.M{"datetime": tFormat}).One(&channelClick)
			err := s.Update(bson.M{"_id": channelClick.Id}, bson.M{"$set": bson.M{"amount": channelClick.Amount + 1}});
			if err != nil {
				fmt.Printf("c.Update(s) err:%+v\n", err)
			}
		}
		gameColl := COLL_GAME_DETAIL + gameId
		m := session.DB("leyoubox").C(gameColl)
		gameDetail := GameDetail{}
		mCount, _ := m.Find(bson.M{"datetime": tFormat}).Count()
		if mCount == 0 {
			gameDetail.Id = bson.NewObjectId()
			gameDetail.DateTime = tFormat
			gameDetail.Amount = 1
			if err := m.Insert(gameDetail); err != nil {
				fmt.Printf("c.Insert(m) err:%+v\n", err)
			}
		} else {
			m.Find(bson.M{"datetime": tFormat}).One(&gameDetail)
			err := m.Update(bson.M{"_id": gameDetail.Id}, bson.M{"$set": bson.M{"amount": gameDetail.Amount + 1}});
			if err != nil {
				fmt.Printf("c.Update(s) err:%+v\n", err)
			}
		}
	}
}

/**
 记录渠道新增用户
 */
func (m *Mongodb) RecordPlayUser(channel string) {
	tFormat := utils.TodayUnix()
	channelColl := COLL_CHANNEL_PLAY_DETAIL + channel
	session := getSession()
	defer session.Close()
	s := session.DB("leyoubox").C(channelColl)
	count, _ := s.Find(bson.M{"datetime": tFormat}).Count()
	channelClick := ChannelClick{}
	if count == 0 {
		channelClick.Id = bson.NewObjectId()
		channelClick.DateTime = tFormat
		channelClick.Amount = 0 //初始化统计数量
		channelClick.User = 1   //用户数量
		if err := s.Insert(channelClick); err != nil {
			fmt.Printf("c.Insert(s) err:%+v\n", err)
		}
	} else {
		s.Find(bson.M{"datetime": tFormat}).One(&channelClick)
		err := s.Update(bson.M{"_id": channelClick.Id}, bson.M{"$set": bson.M{"user": channelClick.User + 1}});
		if err != nil {
			fmt.Printf("c.Update(s) err:%+v\n", err)
		}
	}
}

/**
 记录scene channel对应关系
 */
func (m *Mongodb) UpdateScene(channel string, userId, posterId, goodsId int64) {
	scene := SceneString{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(SCENE_CHANNEL_COLLECTION)
	uChannel := strconv.FormatInt(posterId, 10) + "_" + channel + "_" + strconv.FormatInt(userId, 10) + "_" + strconv.FormatInt(goodsId, 10)
	mCount, _ := c.Find(bson.M{"userid": userId, "scene": uChannel}).Count()
	if mCount == 0 {
		scene.Id = bson.NewObjectId()
		scene.Scene = uChannel
		scene.Channel = channel
		scene.UserId = userId
		scene.GoodsId = goodsId
		if err := c.Insert(scene); err != nil {
			fmt.Printf("c.Insert(m) err:%+v\n", err)
		}
	}
	return
}

/**
 获取或记录用户某款游戏的奖励金币
 */
func (m *Mongodb) CalculateReward(gameId string, userId, reward int64) int64 {
	userReward := UserReward{}
	clickColl := COLL_USER_GAME_REWARD + gameId //用户金币记录
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(clickColl)
	count, _ := c.Find(bson.M{"userid": userId}).Count()
	if count == 0 { //没有记录
		userReward.Id = bson.NewObjectId()
		userReward.UserId = userId
		userReward.Reward = reward
		if err := c.Insert(userReward); err != nil {
			fmt.Printf("userReward c.Insert(b) err:%+v\n", err)
		}
		index := mgo.Index{
			Key:        []string{"userid"},
			Background: true,
		}
		c.EnsureIndex(index)
	} else { //有记录
		c.Find(bson.M{"userid": userId}).One(&userReward)
		reward = userReward.Reward
	}
	return reward
}

/**
 减少游戏奖励金币
 */
func (m *Mongodb) DiminishReward(gameId string, userId int64) {
	userReward := UserReward{}
	clickColl := COLL_USER_GAME_REWARD + gameId //用户金币记录
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(clickColl)
	count, _ := c.Find(bson.M{"userid": userId}).Count()
	if count != 0 {
		var curReward int64
		c.Find(bson.M{"userid": userId}).One(&userReward)
		if userReward.Reward-10 > 0 {
			curReward = userReward.Reward - 10
		}
		err := c.Update(bson.M{"_id": userReward.Id}, bson.M{"$set": bson.M{"reward": curReward}});
		if err != nil {
			fmt.Printf("c.Update(s) err:%+v\n", err)
		}
	}
}

func (m *Mongodb) GetPromoteUser(gameId string, userId int64) []string {
	var reStr []string
	rewards := make([]SdkUserReward, 0)
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	c.Find(bson.M{"inviter": userId, "gameid": gameId}).All(&rewards)
	for i := 0; i < len(rewards); i++ {
		if i == 7 {
			break
		}
		reStr = append(reStr, rewards[i].Avatar)
	}
	return reStr
}

func (m *Mongodb) GetPromoteEarning(gameId string, userId int64) []bson.M {
	var result []bson.M
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	pipe := c.Pipe([]bson.M{{"$match": bson.M{"inviter": userId, "gameid": gameId}}, {"$group": bson.M{"_id": "null", "inviterearn": bson.M{"$sum": "$inviterearn"}}}})
	pipe.All(&result)
	return result
}

func (m *Mongodb) GetGameRewardList(userId int64, gameId string) []SdkUserReward {
	rewards := make([]SdkUserReward, 0)
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	c.Find(bson.M{"inviter": userId, "gameid": gameId}).All(&rewards)
	return rewards
}

func (m *Mongodb) EverPlayed(userId int64, gameId string) bool {
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	count, _ := c.Find(bson.M{"player": userId, "gameid": gameId}).Count()
	if count != 0 {
		return true
	}
	return false
}

func (m *Mongodb) UpdChannelBackground(channel, background string) {
	channelBackground := ChannelBackground{}
	coll := COLL_CHANNEL_BACKGROUND
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(coll)
	channelBackground.Id = bson.NewObjectId()
	channelBackground.Channel = channel
	channelBackground.Background = background
	if err := c.Insert(channelBackground); err != nil {
		fmt.Printf("UpdChannelBackground c.Insert(b) err:%+v\n", err)
	}
	index := mgo.Index{
		Key:        []string{"channel"},
		Background: true,
	}
	c.EnsureIndex(index)
	return
}

func (m *Mongodb) GetChannelBackground(channel string) (string, bool) {
	channelBackground := ChannelBackground{}
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_CHANNEL_BACKGROUND)
	count, _ := c.Find(bson.M{"channel": channel}).Count()
	if count != 0 { //有记录
		err := c.Find(bson.M{"channel": channel}).One(&channelBackground)
		if err != nil {
			return "", false
		} else {
			return channelBackground.Background, true
		}
	}
	return "", false
}

func (m *Mongodb) GetUserGameLog(userId int64) []string {
	var reStr []string
	rewards := make([]SdkUserReward, 0)
	session := getSession()
	defer session.Close()
	c := session.DB("leyoubox").C(COLL_USER_SDK_GAME_LOG)
	c.Find(bson.M{"player": userId}).All(&rewards)
	for i := 0; i < len(rewards); i++ {
		reStr = append(reStr, rewards[i].GameId)
	}
	return reStr
}

//记录每日活跃用户数量
func (m *Mongodb) RecordActiveUser(dlId, today string) {
	channelColl := DAILI_ACTIVE_USER_LOG
	session := getSession()
	defer session.Close()
	s := session.DB("leyoubox").C(channelColl)
	count, _ := s.Find(bson.M{"dlid": dlId, "datetime": today}).Count()
	activeLog := ActiveUserLog{}
	if count == 0 {
		activeLog.Id = bson.NewObjectId()
		activeLog.DateTime = today
		activeLog.DlId = dlId
		activeLog.Count = 1
		if err := s.Insert(activeLog); err != nil {
			fmt.Printf("c.Insert(s) err:%+v\n", err)
		}
		index := mgo.Index{
			Key:        []string{"datetime", "dlid"},
			Background: true,
		}
		s.EnsureIndex(index)
	} else {
		s.Find(bson.M{"dlid": dlId, "datetime": today}).One(&activeLog)
		err := s.Update(bson.M{"_id": activeLog.Id}, bson.M{"$set": bson.M{"count": activeLog.Count + 1}});
		if err != nil {
			fmt.Printf("c.Update(s) err:%+v\n", err)
		}
	}
}